package cate.game.train.yoke;

import cate.common.table.item.yoke.row.YokeGridRow;
import cate.common.util.GameResult;
import cate.game.event.RoleEventPublisher;
import cate.game.event.hero.HeroPowerChangeEvent;
import cate.game.role.Role;
import cate.game.role.bag.hero.Hero;

public class TrainYokeHandler implements RoleEventPublisher {

    public Hero getHero(Role role, String heroUid) {
        return role.getBag().hero.getItem(heroUid);
    }

    public GameResult<Void> on(Role role, String master, String slave, byte pos) {
        GameResult<Void> r = new GameResult<>();
        Hero m = getHero(role, master);
        if (m == null) {
            return r.fail("英雄不存在");
        }
        Hero s = getHero(role, slave);
        if (s == null) {
            return r.fail("羁绊英雄不存在");
        }
        GameResult<Byte> result = m.onYoke(role.toPlayBuildContext(), pos, s);
        if (!result.ok()) {
            return r.fail(result);
        }
        m.getRole().getBase().updatePower();
        publishEvent(role, new HeroPowerChangeEvent(m.getRole(), m));
        role.getHistory().action.teamYokeOn();
        return r;
    }


    public GameResult<Void> off(Role role, String master, byte pos) {
        GameResult<Void> r = new GameResult<>();
        Hero m = getHero(role, master);
        if (m == null) {
            return r.fail("英雄不存在");
        }
        YokeGridRow gridRow = role.getGame().table.yoke.yokeGrid.get((int) pos);
        if (gridRow == null) {
            return r.fail("格子不存在");
        }
        GameResult<Byte> result = m.offYoke(pos);
        if (!result.ok()) {
            return r.fail(result);
        }
        m.getRole().getBase().updatePower();
        publishEvent(role, new HeroPowerChangeEvent(m.getRole(), m));
        return r;
    }

    public GameResult<Void> offAll(Role role, String master) {
        GameResult<Void> r = new GameResult<>();
        Hero m = getHero(role, master);
        if (m == null) {
            return r.fail("英雄不存在");
        }
        GameResult<Byte> result = m.offAllYoke();
        if (!result.ok()) {
            return r.fail(result);
        }
        m.getRole().getBase().updatePower();
        publishEvent(role, new HeroPowerChangeEvent(m.getRole(), m));
        return r;
    }

}
